package com.ruoyi.stock2.thread;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.stock2.domain.DownTradedataSchedule;
import com.ruoyi.stock2.domain.STOCK;
import com.ruoyi.stock2.domain.TRADEDATA;
import com.ruoyi.stock2.domain.TRADEDATA200;
import com.ruoyi.stock2.mapper.DownTradedataScheduleMapper;
import com.ruoyi.stock2.service.ISTOCKService;
import com.ruoyi.stock2.service.ITRADEDATA200Service;
import com.ruoyi.stock2.service.ITRADEDATAService;
import com.ruoyi.stock2.thread.aboutDownloadData.*;
import com.ruoyi.stock2.utils.DateUtils2;
import com.ruoyi.stock2.utils.Sendmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import java.io.UnsupportedEncodingException;
import java.util.List;


public class DownLoadThread implements Runnable {

	private static final Logger log = LoggerFactory.getLogger(DownLoadThread.class);
	boolean working = false;
	ITRADEDATAService itradedataService;
	ITRADEDATA200Service itradedata200Service;
	ISTOCKService istockService;
	DownTradedataScheduleMapper downLoadTradedataScheduleMapper;
	UpdateStocksSymbolDataService updateStocksSymbolDataService;

	public ITRADEDATA200Service getItradedata200Service() {
		return (ITRADEDATA200Service) SpringUtils.getBean(ITRADEDATA200Service.class);
	}
	public ISTOCKService getIstockService() {
		return (ISTOCKService) SpringUtils.getBean(ISTOCKService.class);
	}
	public ITRADEDATAService getItradedataService() {
		return (ITRADEDATAService) SpringUtils.getBean(ITRADEDATAService.class);
	}
	public UpdateStocksSymbolDataService getUpdateStocksSymbolData() {
		return (UpdateStocksSymbolDataService)SpringUtils.getBean(UpdateStocksSymbolDataService.class);
	}
	public DownTradedataScheduleMapper getDownLoadTradedataScheduleMapper() {
		return (DownTradedataScheduleMapper)SpringUtils.getBean(DownTradedataScheduleMapper.class);
	}

	//单例实现 涉及到任务状态
	public static DownLoadThread getInstance() {
		return Singtonle.instance;
	}

	private static class Singtonle {
		private static DownLoadThread instance = new DownLoadThread();
	}

	@Override
	public void run() {
		working = true;
		itradedata200Service = getItradedata200Service();
		istockService = getIstockService();
		itradedataService = getItradedataService();
		downLoadTradedataScheduleMapper = getDownLoadTradedataScheduleMapper();
		updateStocksSymbolDataService = getUpdateStocksSymbolData();
		//获取系统已经完成下载数据日期
		boolean flag = true;
		Integer step_a = null;
		log.warn("任务已执行");
		String downLoadData = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("downLoadData1").getValue();
		String pingjun = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("pingjun2").getValue();
		String priceCompareAverage = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("priceCompareAverage3").getValue();
		String download_schedule = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("download_schedule").getValue();

		if("1".equals(downLoadData)) {
			/* 更新股票单 如果更新了，处在下载数据阶段，那么不再更新股票单*/
			if ("000000".equals(download_schedule)) {
				step_a = updateStockList();
				if (step_a == null) {
					flag = false;
				}
			}
		}
		if(flag) {
			String lastDownLoadDateFromSina = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("lastDownLoadFromSinaDate").getValue();
			String diyDownloadDate = downLoadTradedataScheduleMapper.selectDownTradedataScheduleByName("diyDownloadDate").getValue();
			String now163Date = "";
			if (StringUtils.isEmpty(diyDownloadDate) || "null".equals(diyDownloadDate)) {

			} else {//如果不为空，表示允许交易数据下载到用户自己设定的日期，如下载数据已经隔夜了，需要暂时中断，回头再下载
				now163Date = diyDownloadDate;
			}

			if("1".equals(downLoadData)){
				System.out.println("step_a:"+step_a);
				log.info("lastDownLoadDateFromSina:"+lastDownLoadDateFromSina);
				//下载数据
				DownLoadStockTradeDataFromQQ2.getInstance().run();
				now163Date = DownLoadStockTradeDataFromQQ2.getInstance().getNow163Date();
				log.warn("step_b:截止到"+now163Date+"日数据下载完毕");

				if(now163Date==null || "".equals(now163Date)){
					working = false;
					log.warn("step_b:now163Date error");
					return;
				}
			}
			if("1".equals(pingjun)){
				//补全平均值
				CompPingjun3 cpjt = CompPingjun3.getInstance();
				cpjt.setBeginDateTime(lastDownLoadDateFromSina);
				cpjt.run();
				downLoadTradedataScheduleMapper.updateDownTradedataSchedule(new DownTradedataSchedule("update_average_schedule", "000000"));
			}

			//if("1".equals(priceCompareAverage)){
				//价位与均线比较
				//PriceCompareAverage4 pcat = PriceCompareAverage4.getInstance();
				//pcat.setBeginDateTime(lastDownLoadDateFromSina);
				//pcat.run();
				//downLoadTradedataScheduleMapper.updateDownTradedataSchedule(new DownTradedataSchedule("priceCompareAverageSchedule", "000000"));
			//}


			List<STOCK> stocks = istockService.selectSTOCKList(null);//from stock order by SYMBOL ASC
			long a = System.currentTimeMillis();
			for (STOCK stock : stocks) {
				TRADEDATA tradeDataKey = new TRADEDATA(stock.getSymbol(),
						DateUtils2.formatStringToDate(lastDownLoadDateFromSina, "yyyy-MM-dd"));
				List<TRADEDATA> list = itradedataService.get200ByKeyDateTimeDesc(tradeDataKey);
				//List<TRADEDATA200> list200 = new ArrayList<TRADEDATA200>(30);
				int sizec = list.size()-1;
				for (int i = sizec; i >= 0; i--) {
					TRADEDATA200 tradedata200 = new TRADEDATA200();
					tradedata200.setSymbol(list.get(i).getSymbol());
					tradedata200.setDatetime(list.get(i).getDatetime());
					List<TRADEDATA200> list200s = itradedata200Service.selectTRADEDATA200List(tradedata200);

					if(list200s.size()==0){
						BeanUtils.copyProperties(list.get(i), tradedata200);
						//list200.add(tradedata200);
						itradedata200Service.insertTRADEDATA200(tradedata200);
						log.info("insert to TRADEDATA200：" + list.get(i).getSymbol());
					}else{
                        BeanUtils.copyProperties(list.get(i), tradedata200);
						itradedata200Service.updateTRADEDATA200(tradedata200);
						log.info("update to TRADEDATA200：" + list.get(i).getSymbol());
					}
				}
			}

			long c = System.currentTimeMillis();
			long l2 = (c-a)/1000;
			log.warn("写入tradedata200完毕耗时"+l2+" 秒");
			if(!StringUtils.isEmpty(now163Date)){
				downLoadTradedataScheduleMapper.updateDownTradedataSchedule(new DownTradedataSchedule("lastDownLoadFromSinaDate", now163Date));
			}
			//发送邮件提醒
			try {
				Address[] address = new Address[1];
				Address[] addressbbc = new Address[1];//密送
				for(int i = 0 ; i < 1 ; i++){
					try {
						address[i] = new InternetAddress("cn_wushu@163.com", "denishoh", "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}

				for(int i = 0 ; i < 1 ; i++){
					try {
						addressbbc[i] = new InternetAddress("wushu02@sina.com", "denishoh", "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}


				Sendmail.addressbbc = addressbbc;
				Sendmail.address = address;

				Sendmail.sendDownloadDataOK();
			} catch (Exception e) {
				e.printStackTrace();
			}


		}

		working = false;
	}


	public boolean isWorking() {
		return working;
	}

	public void setWorking(boolean working) {
		this.working = working;
	}

	public Integer updateStockList() {
		int temp_w = 1;
		Integer list_size = null;
		while(temp_w < 5) {

			try {
				list_size = updateStocksSymbolDataService.updateStocksSymbolData();
				downLoadTradedataScheduleMapper.updateDownTradedataSchedule(
						new DownTradedataSchedule("update_symbol_list","更新股票单"+String.valueOf(list_size)+"个"));
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			log.warn("updateStocksSymbolData()=>list_size="+list_size);
			if(list_size == null) {
				log.warn("updateStocks_list_size == null 网络异常");
			}

			if (list_size == 0){
				log.warn("updateStocks_list_size == 0");
			}

			if(list_size != null) {
				break;
			}
			temp_w ++;

		}
		return list_size;
	}
}
